package com.ruoyi.user.service;

import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.user.mapper.UserAddressMapper;
import com.ruoyi.user.domain.UserAddress;

/**
 * 用户地址Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-10
 */
@Service
public class UserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;

    /**
     * 查询用户地址
     *
     * @param addressId 用户地址主键
     * @return 用户地址
     */
    public UserAddress selectUserAddressByAddressId(Long addressId) {
        return userAddressMapper.selectUserAddressByAddressId(addressId);
    }

    /**
     * 查询用户地址列表
     *
     * @param userAddress 用户地址
     * @return 用户地址
     */
    public List<UserAddress> selectUserAddressList(UserAddress userAddress) {
        return userAddressMapper.selectUserAddressList(userAddress);
    }

    /**
     * 新增用户地址
     *
     * @param userAddress 用户地址
     * @return 结果
     */
    public int insertUserAddress(UserAddress userAddress) {
        userAddress.setCreateTime(DateUtils.getNowDate());
        userAddress.setUserId(SecurityUserUtils.getUserId());
        return userAddressMapper.insertUserAddress(userAddress);
    }

    /**
     * 修改用户地址
     *
     * @param userAddress 用户地址
     * @return 结果
     */
    public int updateUserAddress(UserAddress userAddress) {
        userAddress.setUpdateTime(DateUtils.getNowDate());
        return userAddressMapper.updateUserAddress(userAddress);
    }

    /**
     * 批量删除用户地址
     *
     * @param addressIds 需要删除的用户地址主键
     * @return 结果
     */
    public int deleteUserAddressByAddressIds(Long[] addressIds) {
        long userId = SecurityUserUtils.getUserId();
        // 校验地址是否为当前用户
        List<UserAddress> userAddressList = userAddressMapper.selectUserAddressByAddressIds(Arrays.asList(addressIds));
        boolean hasOtherUser = userAddressList.stream().anyMatch(userAddress -> !userAddress.getUserId().equals(userId));
        if (hasOtherUser) {
            throw new ServiceException("删除的地址不是当前用户，无法删除");
        }
        return userAddressMapper.deleteUserAddressByAddressIds(addressIds);
    }
}
